package com.mazegame.frontend;

import com.mazegame.backend.BackgroundPanel;
import com.mazegame.backend.UserDAO;
import com.mazegame.backend.UsersDAO;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.control.Button;


import javax.swing.*;
import java.awt.*;
import java.util.List;


public class RankPanel extends JPanel implements GamePanel{
    private static CardLayout cardLayout;
    private static JPanel cardPanel;
    private JLayeredPane layeredPane;
    private static final int WIDTH = 1500;
    private static final int HEIGHT = 900;
    private JFXPanel jfxPanel;

    // 模拟我的排名相关信息
    private static int myRank = 3; // 假设我的排名是第3名（在前8名范围内）
    private static String myNickname = "我的昵称";
    private static String myPointScore = "800";

    private static VBox scoreRankingPanel;
    private static BorderPane root;

    public RankPanel(CardLayout cardLayout, JPanel cardPanel) {
        this.cardLayout = cardLayout;//
        this.cardPanel = cardPanel;
        initializeUI();
    }

    private void initializeUI() {
        // 使用 JLayeredPane 管理不同层级的组件
        layeredPane = new JLayeredPane();
        setLayout(new BorderLayout());
        add(layeredPane, BorderLayout.CENTER);

        // 创建背景面板并添加到最底层
        BackgroundPanel backgroundPanel = new BackgroundPanel("/img/待机.jpg");
        backgroundPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(backgroundPanel, JLayeredPane.DEFAULT_LAYER);

        // 创建 JavaFX 内容面板（登录界面）
        jfxPanel = new JFXPanel();
        jfxPanel.setOpaque(false); // 确保 JFXPanel 透明
        jfxPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(jfxPanel, JLayeredPane.MODAL_LAYER); // 放在上层

        Platform.runLater(() -> {
            // 创建主容器
            BorderPane root = createContentPane();
            //设置root透明
            root.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");
            // 创建透明场景
            Scene scene = new Scene(root, WIDTH, HEIGHT, Color.TRANSPARENT);
            jfxPanel.setScene(scene);
        });
    }

    private BorderPane createContentPane() {
        root = new BorderPane();
        return root;
    }

    public static void update() {
        Platform.runLater(() -> {
            scoreRankingPanel = createRankingPanel("积分排名", "排名", "昵称", "金币", false);
            HBox rankingBox = new HBox(30);
            rankingBox.setPadding(new Insets(20, 0, 20, 0));
            rankingBox.setAlignment(Pos.CENTER);
            rankingBox.getChildren().addAll(scoreRankingPanel);

            Button backButton = new Button("返回");
            backButton.setFont(Font.font("Arial", FontWeight.NORMAL, 28));
            backButton.setTextFill(Color.BLACK);
            backButton.setPrefSize(240, 60);
            backButton.setOnAction(e -> cardLayout.show(cardPanel, "ENDPANEL"));

            VBox bottomBox = new VBox(10);
            bottomBox.setAlignment(Pos.TOP_CENTER);
            bottomBox.getChildren().add(backButton);
            bottomBox.setPadding(new Insets(-160, 0, 0, 0));

            // 确保 UI 操作在 JavaFX 主线程执行
            root.setCenter(rankingBox);
            root.setBottom(bottomBox);
        });
    }

    public static void update2() {
        Platform.runLater(() -> {
            scoreRankingPanel = createRankingPanel("积分排名", "排名", "昵称", "金币", false);
            HBox rankingBox = new HBox(30);
            rankingBox.setPadding(new Insets(20, 0, 20, 0));
            rankingBox.setAlignment(Pos.CENTER);
            rankingBox.getChildren().addAll(scoreRankingPanel);

            Button backButton = new Button("返回");
            backButton.setFont(Font.font("Arial", FontWeight.NORMAL, 28));
            backButton.setTextFill(Color.BLACK);
            backButton.setPrefSize(240, 60);
            backButton.setOnAction(e -> cardLayout.show(cardPanel, "MAINPANEL"));

            VBox bottomBox = new VBox(10);
            bottomBox.setAlignment(Pos.TOP_CENTER);
            bottomBox.getChildren().add(backButton);
            bottomBox.setPadding(new Insets(-160, 0, 0, 0));

            // 确保 UI 操作在 JavaFX 主线程执行
            root.setCenter(rankingBox);
            root.setBottom(bottomBox);
        });
    }


    private static VBox createRankingPanel(String title, String col1, String col2, String col3, boolean isTimeRanking) {
        // 查询数据库有多少名用户
        int totalUsers = UsersDAO.getTotalUserCount();
        myNickname = LoginPanel.currentUsername;
        myPointScore = String.valueOf(UserDAO.getScore(Integer.parseInt(LoginPanel.currentUserId)));
        myRank = UsersDAO.getUserRankById(Integer.parseInt(LoginPanel.currentUserId));

        // 创建主面板 VBox
        VBox panel = new VBox();
        panel.setPadding(new Insets(20));
        panel.setSpacing(15);

        // 创建标题 Label
        Label titleLabel = new Label(title);
        titleLabel.setFont(Font.font("Arial", FontWeight.BOLD, 48));
        titleLabel.setTextFill(Color.WHITE);
        titleLabel.setPadding(new Insets(10));

        // 创建列标题 HBox
        HBox columnHeaders = new HBox();
        columnHeaders.setSpacing(45);
        columnHeaders.setPadding(new Insets(5));
        columnHeaders.setBorder(new Border(new BorderStroke(Color.WHITE, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));

        Label col1Label = new Label(col1);
        col1Label.setPrefWidth(240);
        col1Label.setAlignment(Pos.CENTER);
        col1Label.setTextFill(Color.WHITE);
        col1Label.setFont(Font.font("Arial", FontWeight.BOLD, 30));

        Label col2Label = new Label(col2);
        col2Label.setPrefWidth(480);
        col2Label.setAlignment(Pos.CENTER_LEFT);
        col2Label.setTextFill(Color.WHITE);
        col2Label.setFont(Font.font("Arial", FontWeight.BOLD, 30));

        Label col3Label = new Label(col3);
        col3Label.setPrefWidth(240);
        col3Label.setAlignment(Pos.CENTER);
        col3Label.setTextFill(Color.WHITE);
        col3Label.setFont(Font.font("Arial", FontWeight.BOLD, 30));

        columnHeaders.getChildren().addAll(col1Label, col2Label, col3Label);

        // 创建排名列表 VBox
        VBox rankingList = new VBox();
        rankingList.setSpacing(10);

        // 添加“我的排名信息”行（在第一名前面显示）
        HBox myRankRow = new HBox();
        myRankRow.setSpacing(45);
        myRankRow.setPadding(new Insets(5));
        myRankRow.setBackground(new Background(new BackgroundFill(Color.rgb(220, 220, 220, 0.7), CornerRadii.EMPTY, Insets.EMPTY))); // 浅灰色背景
        myRankRow.setBorder(new Border(new BorderStroke(Color.GRAY, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT))); // 灰色边框

        Label myRankLabel = new Label(String.valueOf(myRank));
        myRankLabel.setPrefWidth(240);
        myRankLabel.setAlignment(Pos.CENTER);
        myRankLabel.setFont(Font.font("Arial", FontWeight.BOLD, 30));


        Label myNicknameLabel = new Label(myNickname);
        myNicknameLabel.setPrefWidth(480);
        myNicknameLabel.setAlignment(Pos.CENTER_LEFT);
        myNicknameLabel.setFont(Font.font("Arial", FontWeight.BOLD, 30));

        Label myScoreLabel;
        myScoreLabel = new Label(myPointScore);
        myScoreLabel.setPrefWidth(240);
        myScoreLabel.setAlignment(Pos.CENTER);
        myScoreLabel.setFont(Font.font("Arial", FontWeight.BOLD, 30));

        myRankRow.getChildren().addAll(myRankLabel, myNicknameLabel, myScoreLabel);
        rankingList.getChildren().add(myRankRow);


        // 获取当前用户信息并更新
        List<UsersDAO.UserScoreInfo> userScoreInfoList = UsersDAO.getUsersSortedByScore();

        int size = totalUsers;
        if(totalUsers>8){
            size = 8;
        }
        // 添加样例数据（前8名）
        for (int i = 1; i <= size; i++) {
            HBox row = new HBox();
            row.setSpacing(45);
            row.setPadding(new Insets(5));

            Label rankLabel = new Label(String.valueOf(i));
            rankLabel.setFont(Font.font("Arial", FontWeight.LIGHT, 30));
            rankLabel.setPrefWidth(240);
            rankLabel.setAlignment(Pos.CENTER);

            // 生成玩家名称，如果是我的排名则显示我的昵称
            // 获取第i个玩家名称和分数
            String username = userScoreInfoList.get(i - 1).getUsername();
            String score = String.valueOf(userScoreInfoList.get(i - 1).getScore());
            Label nameLabel = new Label(username);
            nameLabel.setFont(Font.font("Arial", FontWeight.LIGHT, 30));
            nameLabel.setPrefWidth(480);
            nameLabel.setAlignment(Pos.CENTER_LEFT);

            // 生成玩家成绩
            Label valueLabel = new Label(score);
            valueLabel.setFont(Font.font("Arial", FontWeight.LIGHT, 30));
            valueLabel.setPrefWidth(240);
            valueLabel.setAlignment(Pos.CENTER);

            // 如果是我的排名，使用特殊样式
            if (i == myRank) {
                nameLabel.setText(myNickname);
                valueLabel.setText(score);
                row.setBackground(new Background(new BackgroundFill(Color.rgb(220, 220, 220, 0.7), CornerRadii.EMPTY, Insets.EMPTY))); // 浅灰色背景
                row.setBorder(new Border(new BorderStroke(Color.GRAY, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT))); // 灰色边框
                rankLabel.setFont(Font.font("Arial", FontWeight.BOLD, 30));
                nameLabel.setFont(Font.font("Arial", FontWeight.BOLD, 30));
                valueLabel.setFont(Font.font("Arial", FontWeight.BOLD, 30));
            } else {
                row.setBackground(new Background(new BackgroundFill(Color.rgb(255, 255, 255, 0.5), CornerRadii.EMPTY, Insets.EMPTY)));
            }
            row.getChildren().addAll(rankLabel, nameLabel, valueLabel);
            rankingList.getChildren().add(row);
        }

        panel.getChildren().addAll(titleLabel, columnHeaders, rankingList);
        panel.setAlignment(Pos.TOP_CENTER);


        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(panel);
        StackPane.setAlignment(panel, Pos.CENTER);


        return panel;
    }




    @Override
    public void showPanel() {
        cardLayout.show(cardPanel, "OPTIONPANEL");
    }

    @Override
    public void cleanup() {

    }
}
